import React from "react";
import ReactDOM from "react-dom";
import AJAX from "../../lib/ajax";
import InfiniteScroll from "./components/InfiniteScroll";
import { addErrorListener } from "../../lib/handleError"
import weixinShare from "../../lib/weixinShare";
require('../../lib/rem')
require('./MyPackage.less')
require('../../styles/common.less')

const AComponentForTest = require('../../components/AComponentForTest')
//无人车
const UnmannedCarOrder = require('./components/UnmannedCarOrder')
//收件
const RecipentCard = require('./components/RecipentCard')
//寄件
// const DeliveryCard = require('./components/DeliveryCard');
const SentOffCard = require('../../components/SendOffCard');
const IconBlock = require('../MyPackage/components/IconBlock')
const mockData = {
    count: 1,//总条数
    unpick_count: 1,//待取件数
    picked_count: 1,//已取件数
    list: [
        {
            id: 1,//订单id,
            state: 1,//订单状态，1未取件，2已取件
            exp_name: "小蜜蜂达",//快递公司名称,
            exp_code: "6666666666666",//快递单号,
            wait_time: "99999999999",// 等待时间,
            out_time: "10",//取件时间,
            storage_info: {
                "type": 1,//存储类型，1柜体2货架，
                "type_desc": "柜体",//存储类型描述, 柜体/货架
                "addr": "案发就开哦啊放假撒娇佛啊时间佛 i 啊说几句始打飞机卡萨飞机卡沙发上",//存放位置,
                "pos_desc": "大家啊时刻发挥空间阿斯顿",//存放位置描述,
                "cell_code": "12",//箱门,
                "pkg_num": "1111",//取件号,
            }
        },
        {
            id: 1,//订单id,
            state: 2,//订单状态，1未取件，2已取件
            exp_name: "小蜜蜂达",//快递公司名称,
            exp_code: "6666666666666",//快递单号,
            wait_time: "99999999999",// 等待时间,
            out_time: "10",//取件时间,
            storage_info: {
                "type": 1,//存储类型，1柜体2货架，
                "type_desc": "柜体",//存储类型描述, 柜体/货架
                "addr": "案发就开哦啊放假撒娇佛啊时间佛 i 啊说几句始打飞机卡萨飞机卡沙发上",//存放位置,
                "pos_desc": "大家啊时刻发挥空间阿斯顿",//存放位置描述,
                "cell_code": "12",//箱门,
                "pkg_num": "1111",//取件号,
            }
        }
    ],
}
class App extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            isMyRecipent: 'RECEIVE',
            //切换 tab 只进行一次请求
            not_load_pickup: true,
            not_load_send: true,
            pickup_load_time: 0,
            sending_load_time: 0,
            wait_package_data: [],
            received_package_data: [],
            unfinished_order: [],
            finished_order: [],
            //title上的数字
            unreceived_num: 0,
            received_num: 0,
            //loadMore
            loadMore_sending_unfinished: false,
            loadMore_sending_finished: false,
            //控制是否显示 no-data 图标
            pickup_no_data: false,
            sending_no_data: false,

            // 无人车订单
            unmanned_status: 0,
            unmanned_no_data: true,
            unmannedList: [],
            unmannedCounts: {
                undelivered: 0,
                delivered: 0,
                cancelled: 0
            },
        }

    }

    //获取我的寄件
    componentWillMount() {
        addErrorListener()()
        weixinShare.hideAll()
        const tag = sessionStorage.getItem('TAG');
        tag && this.setState({
            isMyRecipent: tag
        });
        if (tag === "SENDING") {
            this.getSendingList(1)
            this.setState({
                not_load_send: false
            })
        } else if (tag === "UNMANNED") {
            this.getUnmannedCount();
            this.getUnmannedList(1);
            this.setState({
                unmanned_no_data: false
            })
        } else {
            this.getPickUpList(1)
            this.setState({
                not_load_pickup: false
            })
        }
    }

    componentDidMount() {
        AJAX.appendBaiduAnalysis()
    }

    fetch(key, page_num, cb) {
        let service
        if (key === "SENDING") {
            service = "sending_list"
        } else if (key === "PICKUP") {
            service = "pickup_list"
        }
        let params = {
            page: page_num,
            psize: 10
        }
        AJAX.request(service, params, cb)
    }

    switch(type) {
        return () => {
            this.setState({
                isMyRecipent: type
            });
            sessionStorage.setItem('TAG', type);
            if (type === "RECEIVE") {
                if (this.state.not_load_pickup) {
                    this.getPickUpList(1)
                    this.setState({
                        not_load_pickup: false
                    })
                }
            } else if (type === "SEND") {
                if (this.state.not_load_send) {
                    this.getSendingList(1)
                    this.setState({
                        not_load_send: false
                    })
                }
            }
            else if (type === "UNMANNED") {
                this.getUnmannedCount();
                if (this.state.unmanned_no_data) {
                    this.getUnmannedList(1);
                    this.setState({
                        unmanned_no_data: false
                    })
                }
            }
        }
    }

    //待收包裹
    translateUnreceivedPackages(list = []) {
        return list.map((item) => {
            let label_name, label_number
            if (item.storage_info.type === 2) {
                //货架，有取件号
                label_name = "取件号"
                label_number = item.storage_info.pkg_num
            } else if (item.storage_info.type === 1) {
                //柜体，有箱门号
                label_name = "箱门号"
                label_number = item.storage_info.cell_code
            } else if (item.storage_info.type === 3) {
                //地堆
                label_name = "地堆号"
                label_number = item.storage_info.pkg_num
            }
            return {
                order_id: item.id,
                state: item.state,
                type: item.storage_info.type,
                order_type: item.order_type,
                title: item.storage_info.addr,
                express_company: item.exp_name,
                express_number: item.exp_code,
                wait_time: item.wait_time,
                label_name,
                label_number,
            }
        })
    }

    //已收包裹
    translateReceivedPackages(list = []) {
        return list.map((item) => {
            return {
                mode: "todo",
                order_id: item.id,
                order_type: item.order_type,
                state: item.state,
                title: item.storage_info.addr,
                express_company: item.exp_name,
                express_number: item.exp_code,
                receive_time: item.out_time,
            }
        })
    }

    //未完成订单
    translateUnfinishedOrders(list = []) {
        return list.map((item) => {
            let flag_type, btn_type
            switch (item.status) {
                case 100:
                    flag_type = "AlreadyOrder"
                    btn_type = item.type == 3 ? "PutIn" : "CancelOrder"
                    break
                case 110:
                    flag_type = "WaitPay"
                    btn_type = "Pay"
                    break
                case 120:
                    flag_type = "AlreadyStart"
                    btn_type = item.can_comment === 1 ? "Evalute" : "ViewEvalute"
                    break
                case 125:
                    flag_type = "AlreadyStart"
                    btn_type = "GetBack"
                    break
                case 130:
                    flag_type = "OnDistributing",
                        btn_type = item.can_comment === 1 ? "Evalute" : "ViewEvalute"
                    break
                case 140:
                    flag_type = "AlreadySign",
                        btn_type = item.can_comment === 1 ? "Evalute" : "ViewEvalute"
                    break
                case 150:
                    flag_type = "AlreadyCancel",
                        btn_type = "DeleteRecord"
            }
            return {
                flag_type: flag_type,
                btn_type: btn_type,
                order: item.id,
                order_num: item.order_num,
                from_city: item.sender_addr.area_name,
                to_city: item.consignee_addr.area_name,
                from_name: item.sender_addr.realname,
                to_name: item.consignee_addr.realname,
                log_info: item.desc_content,
                log_time: item.desc_time,
                type: item.type,    //运单类型（1:国内 2:国际 3:柜体）,
                send_type_desc: item.send_type_desc,    //str 寄件方式描述(服务网点寄件、智能柜寄件),
                status_list: item.status_list,  //用于显示的状态列表
            }
        })
    }

    //获取我的寄件
    getSendingList(page_num) {
        this.fetch("SENDING", page_num, (data) => {
            //返回的列表混合了待收和已收包裹
            const mixed_list = (data.body.list || []).filter(order => order.send_type != 1);
            let sending_unfinished_list = [], sending_finished_list = []
            mixed_list.forEach(item => {
                if (item.state === 1) {
                    //未完成寄件
                    sending_unfinished_list.push(item)
                } else if (item.state === 2) {
                    //已完成寄件
                    sending_finished_list.push(item)
                }
            })
            let sending_unfinished_order = this.translateUnfinishedOrders(sending_unfinished_list)
            let sending_finished_order = this.translateUnfinishedOrders(sending_finished_list)
            //合并已存在的 card
            const past_sending_unfinished_order = this.state.sending_unfinished_order || []
            const past_sending_finished_order = this.state.sending_finished_order || []
            if (past_sending_unfinished_order.length > 0) {
                sending_unfinished_order = past_sending_unfinished_order.concat(sending_unfinished_order)
            }
            if (past_sending_finished_order.length > 0) {
                sending_finished_order = past_sending_finished_order.concat(sending_finished_order)
            }
            //判断是否显示 no-data 
            if (page_num === 1 && mixed_list.length === 0) {
                this.setState({
                    sending_unfinished_order,
                    sending_finished_order,
                    unfinished_count: data.body.unfinished_count,
                    finished_count: data.body.finished_count,
                    sending_no_data: true
                })
            } else {
                this.setState({
                    sending_unfinished_order,
                    sending_finished_order,
                    unfinished_count: data.body.unfinished_count,
                    finished_count: data.body.finished_count,
                })
            }
        })
    }

    //获取我的收件
    getPickUpList(page_num) {
        this.fetch("PICKUP", page_num, (data) => {
            //返回的列表混合了待收和已收包裹
            const mixed_list = data.body.list || []
            // const mixed_list = mockData.list     //假数据
            let pickup_unfinished_list = [], pickup_finished_list = []
            mixed_list.forEach(item => {
                if (item.state === 1) {
                    //待收包裹
                    pickup_unfinished_list.push(item)
                } else if (item.state === 2) {
                    //已收包裹
                    pickup_finished_list.push(item)
                }
            })
            let pickup_unfinished_order = this.translateUnreceivedPackages(pickup_unfinished_list)
            let pickup_finished_order = this.translateReceivedPackages(pickup_finished_list)
            //合并已存在的 card
            const past_pickup_unfinished_order = this.state.pickup_unfinished_order || []
            const past_pickup_finished_order = this.state.pickup_finished_order || []
            if (past_pickup_unfinished_order.length > 0) {
                pickup_unfinished_order = past_pickup_unfinished_order.concat(pickup_unfinished_order)
            }
            if (past_pickup_finished_order.length > 0) {
                pickup_finished_order = past_pickup_finished_order.concat(pickup_finished_order)
            }
            //判断是否显示 no-data 
            if (page_num === 1 && mixed_list.length === 0) {
                this.setState({
                    pickup_unfinished_order,
                    pickup_finished_order,
                    picked_count: data.body.picked_count,
                    unpick_count: data.body.unpick_count,
                    pickup_no_data: true
                })
            } else {
                this.setState({
                    pickup_unfinished_order,
                    pickup_finished_order,
                    picked_count: data.body.picked_count,
                    unpick_count: data.body.unpick_count,
                })
            }
        })
    }


    // 无人车订单统计
    getUnmannedCount() {
        AJAX.request('unmanned_count', {}, (data) => {
            const unmannedCounts = {
                undelivered: data.body[0].count,
                delivered: data.body[1].count,
                cancelled: data.body[2].count,
            };
            this.setState({ unmannedCounts });
        });
    }

    //获取无人车订单
    getUnmannedList(page_num, status = 0) {
        const params = {
            current: page_num,
            pageSize: 10,
            status: status
        }, { unmannedList } = this.state;
        AJAX.request("unmanned_query", params, (data) => {

            if (page_num === 1 && (!data.body || data.body.count === 0)) {
                this.setState({ unmanned_no_data: true, unmannedList: [] });
                return;
            }

            let new_unmannedList = [];
            if (page_num === 1) {
                new_unmannedList = data.body.list || [];
            }
            if (page_num > 1) {
                new_unmannedList = new_unmannedList.concat(unmannedList, data.body.list || []);
            }

            this.setState({
                unmanned_no_data: false,
                unmannedList: new_unmannedList
            });
        })
    }


    jumpUnmannedDetail(order_id) {
        const wx_type = window.localStorage.getItem('wx_type');
        return () => {
            window.location.href = `./UnmannedCarDetail?order_id=${order_id}&wx_type=${wx_type}`;
        }
    }

    jumpRecipentDetail(state, order_id, out_time) {
        const wx_type = window.localStorage.getItem('wx_type');
        if (state === 1) {
            return () => {
                window.location.href = `./PickUpDetail?order_id=${order_id}&wx_type=${wx_type}`;
            }
        } else if (state === 2) {
            return () => {
                window.location.href = `./MyPackageRecipentDetail?order_id=${order_id}&out_time=${out_time}&wx_type=${wx_type}`
            }
        }
    }

    jumpDeliveryDetail(order_id, type) {
        return () => {
            window.location.href = './MyPackageDeliveryDetail?order_id=' + order_id + '&type=' + type
        }
    }

    loadMorePickup() {
        const pickup_unfinished_order = this.state.pickup_unfinished_order || []
        const pickup_finished_order = this.state.pickup_finished_order || []
        const current_count = pickup_finished_order.length + pickup_unfinished_order.length
        const total_count = this.state.picked_count + this.state.unpick_count
        if (current_count < total_count) {
            const num = current_count / 10 + 1
            this.getPickUpList(num)
        }
    }

    loadMoreSending() {
        const sending_unfinished_order = this.state.sending_unfinished_order || []
        const sending_finished_order = this.state.sending_finished_order || []
        const current_count = sending_unfinished_order.length + sending_finished_order.length
        const total_count = this.state.unfinished_count + this.state.finished_count
        if (current_count < total_count) {
            const num = current_count / 10 + 1
            this.getSendingList(num)
        }
    }

    loadMoreUnmanned(total_count, status) {
        if (this.state.unmannedList.length < 10) { return; }
        if (this.state.unmannedList.length < total_count) {
            const num = parseInt(this.state.unmannedList.length / 10) + 1
            this.getUnmannedList(num, status);
        }
    }

    receive() {
        const pickup_unfinished_order = this.state.pickup_unfinished_order || []
        const pickup_finished_order = this.state.pickup_finished_order || []
        let unfinished_content = null, finished_content = null, loadMore_func = this.loadMorePickup.bind(this)
        let has_more = false
        const loader = <div className="loader"><i className="weui-loading"></i></div>
        //成功返回数据才 render
        if (pickup_unfinished_order.length > 0) {
            unfinished_content = this.pickupTemplate(pickup_unfinished_order, "待收包裹", this.state.unpick_count)
        }
        if (pickup_finished_order.length > 0) {
            finished_content = this.pickupTemplate(pickup_finished_order, "已收包裹", this.state.picked_count)
        }
        //判断是否需要加载更多
        const total_count = this.state.picked_count + this.state.unpick_count
        if (pickup_finished_order.length + pickup_unfinished_order.length < total_count) {
            has_more = true
        } else {
            has_more = false
        }
        let content =
            <InfiniteScroll
                threshold={15}
                loadMore={loadMore_func}
                hasMore={has_more}
                loader={loader}>
                {unfinished_content}
                {finished_content}
            </InfiniteScroll>
        //是否展示 no-data
        if (this.state.pickup_no_data) {
            content = <IconBlock type="NO-DATA" />
        }
        return (
            <div className="weui-tab__panel">
                {content}
            </div>
        )
    }

    send() {
        const unfinished_order = this.state.sending_unfinished_order || []
        const finished_order = this.state.sending_finished_order || []
        let unfinished_content = null, finished_content = null, loadMore_func = this.loadMoreSending.bind(this)
        let has_more = false
        const loader = <div className="loader"><i className="weui-loading"></i></div>
        //成功返回数据才 render
        if (unfinished_order.length > 0) {
            unfinished_content = this.deliveryTemplate(unfinished_order, "未完成", this.state.unfinished_count)
        }
        if (finished_order.length > 0) {
            finished_content = this.deliveryTemplate(finished_order, "已完成", this.state.finished_count)
        }
        const total_count = this.state.unfinished_count + this.state.finished_count
        if (unfinished_order.length + finished_order.length < total_count) {
            has_more = true
        } else {
            has_more = false
        }
        let content =
            <InfiniteScroll
                threshold={15}
                loadMore={loadMore_func}
                hasMore={has_more}
                loader={loader}>
                {unfinished_content}
                {finished_content}
            </InfiniteScroll>
        //是否展示 no-data
        if (this.state.sending_no_data) {
            content = <IconBlock type="NO-DATA" />
        }
        return (
            <div className="weui-tab__panel">
                {content}
            </div>
        )
    }



    unmanned() {
        const { unmannedList, unmannedCounts, unmanned_status } = this.state;
        let has_more = false, loadMore_func = null;
        const loader = <div className="loader"><i className="weui-loading"></i></div>;
        let unmanned_content = null;
        unmanned_content = this.unmannedTemplate(unmannedList);

        switch (unmanned_status) {
            case 0:
                if ((unmannedCounts.undelivered + unmannedCounts.delivered + unmannedCounts.cancelled) > unmannedList.length) {
                    has_more = true;
                } else {
                    has_more = false;
                }
                loadMore_func = this.loadMoreUnmanned(unmannedCounts.undelivered + unmannedCounts.delivered + unmannedCounts.cancelled, unmanned_status);
                break;
            case 1:
                if ((unmannedCounts.undelivered) > unmannedList.length) {
                    has_more = true;
                } else {
                    has_more = false;
                }
                loadMore_func = this.loadMoreUnmanned(unmannedCounts.undelivered, unmanned_status);
                break;
            case 2:
                if ((unmannedCounts.delivered) > unmannedList.length) {
                    has_more = true;
                } else {
                    has_more = false;
                }
                loadMore_func = this.loadMoreUnmanned(unmannedCounts.delivered, unmanned_status);
                break;
            case 3:
                if ((unmannedCounts.cancelled) > unmannedList.length) {
                    has_more = true;
                } else {
                    has_more = false;
                }
                loadMore_func = this.loadMoreUnmanned(unmannedCounts.cancelled, unmanned_status);
                break;
        };
        let content =
            <InfiniteScroll
                threshold={15}
                loadMore={loadMore_func}
                hasMore={has_more}
                loader={loader}>
                {unmanned_content}
            </InfiniteScroll>
        //是否展示 no-data
        if (this.state.unmanned_no_data) {
            content = <IconBlock type="NO-DATA" />
        }
        return (
            <div className="weui-tab__panel" style={{ paddingTop: '62px' }}>
                <div className="unmanned-content">
                    <div className="weui-navbar">
                        <div className={(unmanned_status === 0)
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={() => {
                                this.switchUnmannedStatus(0);
                            }}>
                            全部
                        </div>
                        <div className={(unmanned_status === 1)
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={() => {
                                this.switchUnmannedStatus(1);
                            }}>
                            待送达
                            {unmannedCounts.undelivered > 0 && <div className="badge">{unmannedCounts.undelivered}</div>}
                        </div>
                        <div className={(unmanned_status === 2)
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={() => {
                                this.switchUnmannedStatus(2);
                            }}>
                            已完成
                        </div>
                        <div className={(unmanned_status === 3)
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={() => {
                                this.switchUnmannedStatus(3);
                            }}>
                            已取消
                        </div>
                    </div>
                    {content}
                </div>
            </div >
        )
    }

    switchUnmannedStatus(status) {
        this.setState({ unmanned_status: status });
        this.getUnmannedList(1, status);
    }

    //  无人车订单区域
    unmannedTemplate(order_list = []) {
        const cards = order_list.map((item, index) =>
            <UnmannedCarOrder dataSource={item} key={`unmanned_card_${index}`}
                onClick={this.jumpUnmannedDetail(item.orderId)} />)
        const content =
            <div className="unmanned-list">
                {cards}
            </div>
        return content
    }

    //生成收件区域
    pickupTemplate(order_list = [], text = "未收包裹", count) {
        const cards = order_list.map((item, index) =>
            <RecipentCard dataSource={item} key={`recipent_card_${index}`}
                onClick={this.jumpRecipentDetail(item.state, item.order_id, item.receive_time)} />)
        const content =
            <div>
                <div className="recipient-number">
                    {text}({count})
                </div>
                {cards}
            </div>
        return content
    }

    //生成寄件区域
    deliveryTemplate(order_list = [], text = "未完成", count) {
        const cards = order_list.map((item, index) => {
            item.info_tips = true;  //状态显示
            item.btn_show = true;    //按钮显示
            return (
                <SentOffCard dataSource={item} key={`delivery_card_${index}`}
                    onClick={this.jumpDeliveryDetail(item.order, item.type)} />
            )
        }
        )
        const content =
            <div>
                <div className="recipient-number borderB">
                    {text}({count})
                </div>
                <div className="delivery-cards">
                    {cards}
                </div>
            </div>
        return content
    }

    render() {
        const receive_cards = this.receive();
        const send_cards = this.send();
        const unmanned_cards = this.unmanned();
        return (
            <div className="MyPackage">
                <div className="weui-tab">
                    <div className="weui-navbar">
                        <div className={(this.state.isMyRecipent === 'RECEIVE')
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={this.switch("RECEIVE")}>
                            我的快递
                        </div>
                        <div className={(this.state.isMyRecipent === 'SEND')
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={this.switch("SEND")}>
                            我的寄件
                        </div>
                        <div className={(this.state.isMyRecipent === 'UNMANNED')
                            ? "weui-navbar__item weui-bar__item_on"
                            : "weui-navbar__item"} onClick={this.switch("UNMANNED")}>
                            无人车订单
                        </div>
                    </div>
                    {this.state.isMyRecipent === 'RECEIVE' ? receive_cards : this.state.isMyRecipent === 'SEND' ? send_cards : unmanned_cards}
                </div>
            </div>
        )
    }
}
ReactDOM.render(<App />, document.getElementById('app'))
if (module.hot) {
    module.hot.accept();
}